<?php
define('FS_METHOD', 'direct');
/*
bug：
1.添加日期貌似有问题，有待测试
2.通过输入方式添加了5个以上的标签
*/

//判断是否开启游客投稿
if ( !is_user_logged_in() ) {
	if (get_option('txtjee_guestpost') == "Off"){
		header( 'Location: ' . wp_login_url( get_permalink() ) );
	}
}

if( isset($_POST['p_form']) && $_POST['p_form'] == 'send'){
	global $wpdb;
	$last_post = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC LIMIT 1");

	/* 投稿时间间隔
	if ( current_time('timestamp') - strtotime($last_post) < 5 ){
		wp_die('您投稿也太勤快了吧，先歇会儿！<br /><br /><a href="javascript:history.back();">返回上页&gt;&gt;</a>');
	}*/

	// 表单变量初始化
	$title		= isset( $_POST['p_title'] ) ? trim(htmlspecialchars($_POST['p_title'], ENT_QUOTES)) : '';
	$content	= isset( $_POST['p_content'] ) ? str_replace('  ','　',htmlspecialchars($_POST['p_content'], ENT_QUOTES)) : '';
	$excerpt	= isset( $_POST['p_excerpt'] ) ? trim(htmlspecialchars($_POST['p_excerpt'], ENT_QUOTES)) : '';
	$tags		= isset( $_POST['p_tags'] ) ? str_replace('，',',',trim(htmlspecialchars($_POST['p_tags'], ENT_QUOTES))) : '';
	$pic		= isset( $_POST['p_pic'] ) ? (int)$_POST['p_pic'] : '';
	$category	= isset( $_POST['p_cat'] ) ? (int)$_POST['p_cat'] : 0;

	// 判断是否注册会员
	global $user_email, $user_identity;
	if ( !is_user_logged_in() ) {
		$name	= isset( $_POST['p_authorname'] ) ? trim(htmlspecialchars($_POST['p_authorname'], ENT_QUOTES)) : '';
		$email	= isset( $_POST['p_authoremail'] ) ? trim(htmlspecialchars($_POST['p_authoremail'], ENT_QUOTES)) : '';
		if ( mb_strlen($name) > 60 ){
			wp_die('有这么长的名字吗？<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
		}

		if ( !empty( $email) || strlen($email) > 200 ){
			if ( !preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email) ){
				wp_die('电子邮箱格式错误。<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
			}
		}
	}else{
		$name = $user_identity;
		$email = $user_email;
	}

	// 表单项数据验证
	if ( empty($content) ){
		wp_die('内容不能为空。<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
	}

	if ( $category < 0 ){
		wp_die('请选择分类。<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
	}

	//if ( strlen($excerpt) > 130 ){
	//	wp_die('摘要请控制在130字以内。<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
	//}

	//插入投稿者信息及宣传语
	$ps = chr(10) . chr(10) . '<p class="ymwz-link">';
	$pe = '</p>';
	$thank = (!empty( $name )) ? chr(10) . chr(10) . '<p class="author">感谢<span class="name">' . $name . '</span>的投稿 :)</p>' : '';
	$link = '<a href="' . get_bloginfo('siteurl') . '/" target="_blank">' . get_bloginfo('name') . '</a>';
	$text = array(
		$ps . '进入' . $link . '，阅读更多好文章' . $pe,
		$ps . $link . '，原创诗文天地' . $pe,
		$ps . '本文来自：' . $link . $pe,
		$ps . '优美的文字与您分享，' . $link . $pe,
		$ps . $link . '，分享你的故事' . $pe,
	);
	$rt = $text[rand( 0 , count($text) - 1 ) ];
	$p = array(
		'post_title'	=> $title,
		'post_content'	=> $content .$thank . $rt,
		'post_excerpt'	=> $excerpt,
		'post_category'	=> array($category),
		'tags_input'	=> $tags,
		'post_author'	=> is_user_logged_in() ? $user_id : 2,	//如是快速投稿，将文章分配给ID为2的用户
		'post_status'	=> 'pending'	//审稿状态
	);

	// 将文章插入数据库
	$newPost = wp_insert_post( $p );

	if ( $newPost != 0 ){
		// 插入图片
		if ( $_SERVER['REQUEST_METHOD'] == 'POST' && is_uploaded_file( $_FILES["p_pic"][tmp_name] ) ) {	//是否存在文件 

			// 加载库
			require_once (ABSPATH.'/wp-admin/includes/media.php');
			require_once (ABSPATH.'/wp-admin/includes/file.php');
			require_once (ABSPATH.'/wp-admin/includes/image.php');

			// 开始上传
			$attachment = media_handle_upload( 'p_pic', $newPost, array( 'post_title' => $title ) );	//中文文件名在Windows主机上传出错

			// 判断是否图片
			if ( !is_wp_error($attachment) && wp_attachment_is_image($attachment) ) {

				$upload_dir = wp_upload_dir();

				// 获取旧图片地址
				$file = get_attached_file($attachment);
				$path = pathinfo($file);

				// 生成新图片地址
				$newfilename = strtotime("now") . $attachment;
				$newfile = $path['dirname'] . "/" . $newfilename . "." . $path['extension'];

				// 修改图片字段中的地址为新地址
				if ( rename( $file, $newfile ) ){

					// 获取缩略图信息
					$pm = get_post_meta( $attachment , "_wp_attachment_metadata" , true );
					if ( $pm['sizes'] ){
						foreach( $pm['sizes'] as $size => $pm_size ){	//遍历$pm['sizes']里的元素信息
							$newthumb = $newfilename . "-" . $pm_size['width'] . "x" . $pm_size['height'] . "." . $path['extension'];
							if ( rename( $path['dirname'] . "/" . $pm_size['file'] , $path['dirname'] . "/" . $newthumb ) ) {
								$pm['sizes'][$size]['file'] = $newthumb;
							}
						}
					}
					$pm['file'] = _wp_relative_upload_path($newfile);
					update_post_meta( $attachment, "_wp_attachment_metadata" , $pm );
					update_attached_file( $attachment, $newfile );

					// 修改 posts表 guid字段
					$attachment_record = & $wpdb->get_row( $wpdb -> prepare( "UPDATE $wpdb->posts SET guid='%s' WHERE ID = %d ", $upload_dir['baseurl'] . "/" . $pm['file'] , $attachment ) );

					// 设置特色图片
					set_post_thumbnail( $newPost, $attachment );

					// 将图片插入到文章
					$pic = wp_get_attachment_image( $attachment, 'large' );
					$p = array(
						'ID' => $newPost,
						'post_content' => $pic . chr(10) . chr(10) . $content .$thank . $rt,
					);
					wp_update_post( $p );
					unset($_FILES);
				}
			} else {
				wp_delete_attachment($attachment);
				wp_delete_post($newPost);
				wp_die('图片格式错误。<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
			}
		}

		// 如果不是注册会员，将用户信息添加到自定义字段
		if ( !is_user_logged_in() ){
			if (!empty( $name )) add_post_meta($newPost, 'name', $name); //昵称
			if (!empty( $email )) add_post_meta($newPost, 'email', $email); //邮件
		}
		add_post_meta($newPost, 'ip', $_SERVER['REMOTE_ADDR']);	//IP

		//发送投稿成功邮件
		if ( !empty($email) ){
			$subject = '[' . get_option('blogname') . '] 感谢您的来稿！';
			$message = '
			<div style="color:#100;background-color:#F9F9F9;border:1px solid #EEE;padding:10px;margin: 0 0 20px 0;">
				<p>您的稿件已投递成功，小编正在审核中，请耐心等待。</p>
				<p>您的投稿内容如下：</p>
			</div>
			<div style="color:#100;background-color:#F9F9F9;border:1px solid #EEE;padding:10px;margin: 0 0 20px 0;">
				<strong>' . $title . '</strong><hr />
				' . nl2br( $content ) . '
			</div>
			<p><strong>温馨提示：本邮件由系统自动发送，请勿直接回复！</strong></p>
			<p>欢迎 <a href="http://mail.qq.com/cgi-bin/bookcol?colid=20277" target="_blank">订阅</a> 本站，欢迎再次光临 <a href="' . get_option('home') . '" target="_blank">' . get_option('blogname') . '</a>！</p> 
			<p>&copy; <strong><a href="' . get_option('home') . '" target="_blank">' . get_option('blogname') . '</a></strong></p> 
			';
			$from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
			$headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";

			wp_mail($email, $subject, $message, $headers);
		}

		//投稿成功
		wp_die('<strong style="color:#090;">感谢您的来稿，小编正在审核，请耐心等待。</strong><br /><br /><a href="/submit">再投一稿&gt;&gt;</a><br /><a href="/">返回首页&gt;&gt;</a>' , '投稿成功');
	}else{

		//投稿失败
		wp_die('投稿失败！<br /><br /><a href="javascript:history.back();">返回修改&gt;&gt;</a>');
	}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>投稿至<?php bloginfo('name'); ?></title>
<link rel="shorcut icon" href="<?php bloginfo('template_url'); ?>/images/favicon.ico" type="image/x-ico" />
<link rel="stylesheet" type="text/css" media="screen" href="<?php bloginfo('template_url'); ?>/style.css" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/includes/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/includes/jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
	$("#p_authorname").val($.cookie("name"));
	$("#p_authoremail").val($.cookie("mail"));
	$("#p_authorblog").val($.cookie("blog"));
	
	var limitNum = 130;
	var pattern = '<strong>' + limitNum + '</strong> 字以内';
	$('#p_excerpt_chk').html(pattern);
	$('#p_excerpt').keyup(
		function(){
			var remain = $(this).val().length;
			if (remain > limitNum){
				var result = limitNum - remain;
				pattern = '已超过 <strong class="e">' + -result + '</strong> 字';
			}else {
				var result = limitNum - remain;
				pattern = '还可以输入 <strong>' + result + '</strong> 字';
			}
			$('#p_excerpt_chk').html(pattern);
		}
	);
});
function PostDoIt(){
	$.cookie("name", $("#p_authorname").val());
	$.cookie("mail", $("#p_authoremail").val());
	$.cookie("blog", $("#p_authorblog").val());
}

//http://mrthink.net/jquery-plugin-iselecttags/
//调用bgIframe,解决IE6下遮住下拉列表的问题
;(function($){
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};
})(jQuery);

//选择标签至文本域插件
;(function(){
	$.fn.extend({
		iSelectTags:function(options){
			var iset={
				name:'#p_tags',//表单或class或id名
				drop:$('#CommonTags'),//弹出框定位
				pseudoClass:$('#CommonTags>p>span'),//可选择的标签定位
				close:$('.close'),//关闭按钮定位
				separator:',',//标签间分隔符,建议使用英文逗号
				maxCount:5//默认限制个数,也可以设置表单的data-count值覆盖默认值
			}
            options=$.extend(iset, options || {});

			var _input=$(iset.name);
			var _inputVal=_input.val();
			var _arr=new Array(); //存放标签的数组
			var _left=_input.offset().left; //左绝对距离
			var _top=_input.offset().top+_input.outerHeight(); //上绝对距离,此处要加上表单的高度
			var _dropW=_input.outerWidth()-parseInt(_input.css('border-left-width'))-parseInt(_input.css('border-right-width'))-parseInt(iset.drop.css('paddingLeft'))-parseInt(iset.drop.css('paddingRight'));
			iset.drop.css({'position':'absolute','left':_left+'px','top':_top+'px','width':_dropW+'px'});
			//弹出框的宽度,此处计算的是与表单实际宽度相等的.也可以直接在样式中定义.
			var _txt=null;
			var _maxCount=parseInt(_input.attr('data-count'));//限制选择个数
			if(isNaN(_maxCount)){
				_maxCount=iset.maxCount
			}
			
			_input.click(function(){
				iset.drop.show();
				iset.drop.bgiframe();//调用bgiframe插件,解决ie6下select的z-index无限大问题
            }).bind('keyup change',function(){
				//可以在此处扩展手动输入标签情况下的相关判断
				//if语句可避免清空重新选择时第一个字符为逗号
				if ($(this).val() == '') {
					_arr = new Array();
				}else {
					_arr = $(this).val().split(iset.separator);//当用户手动删除或修改标签值后更新标签值
				}
			});
			
			$(document).click(function(e){
				//点击非弹出框区域时关闭弹出框
				//下面的 if语句是用来判断传入的是class还是id
				if(iset.name.charAt(0)=='#'){
					if(e.target.id!=iset.name.substring(1)){
						iset.drop.hide();
						}
				}else if(iset.name.charAt(0)=='.'){
					if(e.target.className!=iset.name.substring(1)){
						iset.drop.hide();
					}
				}
			});
			
			iset.drop.click(function(e){
				//阻止弹出框区域默认事件
				e.stopPropagation();
			});
			
			iset.pseudoClass.click(function(){
				//标签选择
				_txt=$(this).text();
				//下面的$.inArray是用来判断是否重复
				//若想反馈重复提示或走出限制个数提示,可改进下面的if语句
				if(($.inArray(_txt,_arr)==-1) && (_arr.length<_maxCount )){
					_arr.push(_txt);
					_inputVal=_arr.join(iset.separator);
					_input.val(_inputVal);
				}
				
			});
			//关闭按钮
			iset.close.click(function(){
				iset.drop.hide();
			});
		}
	});
})(jQuery);

//插件调用
$(function(){
	$("#PostForm").iSelectTags();
});

//离开页面时提示保存信息
$(function(){
	//开始绑定
	$("input[type='text'],textarea").each(function(){
		$(this).change(function(){
			allowUnload();
		}); 
	});
	//form提交时解除绑定
	$("#PostForm").submit(function(){
		$(window).unbind("beforeunload");
	});
});
function allowUnload(){
	$(window).bind("beforeunload", function(){ 
		return "您的投稿还没有提交，内容将丢失！"; 
	});
}
</script>
</head>
<body class="contribute-submit">
<div class="submit-main">
	<h1>投稿 至 <?php bloginfo('name'); ?><span><a href="<?php echo get_option('home'); ?>/" title="返回 <?php bloginfo('name'); ?> 首页 ">返回首页</a></span></h1>
	<div class="require">
 		<div class="passport">
<?php global $user_ID, $user_identity, $user_level ?>
<?php if ( is_user_logged_in() ):?>
			<p>Hi，<a href="<?php echo admin_url(); ?>profile.php" target="_blank"><?php echo $user_identity ?></a>！<a href="<?php echo wp_logout_url( get_permalink() ); ?>">退出</a> <a href="<?php echo home_url(); ?>/author/<?php echo $user_login ?>" target="_blank">专栏</a></p>
<?php else: ?>
			<p><a href="<?php echo wp_login_url( get_permalink() ); ?>">请登录</a> 或 <a href="/wp-login.php?action=register">免费注册</a></p>
			<p>注册会员可拥有自己的作者专栏。</p>
<?php endif; ?>
		</div>
		<?php if (have_posts()) the_post(); update_post_caches($posts); the_content(); ?><?php edit_post_link('编辑','<p>','</p>'); ?>
	</div>
	<form action="<?php echo $_SERVER["REQUEST_URI"]; ?>" method="POST" id="PostForm" onSubmit="PostDoIt();" enctype="multipart/form-data">
		<div class="item">
			<label for="p_title">标题<span>如不填则为无题诗文</span></label>
			<input type="text" id="p_title" name="p_title" />
		</div>
		<div class="item">
			<label for="p_content">内容<span>段落之间空一行，每段开头不空两个字，所有标点都是中文标点</span></label>
			<textarea id="p_content" name="p_content"></textarea>
		</div>
		<div class="item">
			<label for="p_cat">分类<span>必选项</span></label>
			<div class="sel"><?php wp_dropdown_categories('name=p_cat&id=p_cat&show_option_none=请选择分类&exclude=1,398'); ?></div>
		</div>
		<div class="item">
			<label for="p_excerpt">摘要<span>内容里的一段精彩文字或引言</span><span id="p_excerpt_chk"></span></label>
			<textarea name="p_excerpt" id="p_excerpt"></textarea>
		</div>
		<div class="item">
			<label for="p_tags">标签<span>最多5个，每个标签用逗号分隔</span></label>
			<input type="text" id="p_tags" name="p_tags" data-count="5" autocomplete="off" />
			<div class="info tags" id="CommonTags">
				<div class="tags-title">
					<h3>常用标签</h3>
					<div class="close">关闭</div>
				</div>
				<p><?php
	$tag = wp_tag_cloud('format=array&number=60&orderby=count&order=DESC');
	foreach($tag as $color){
		$color = eregi_replace("<a[^>]*>([^<]*)</a>","<span>\\1</span>",$color);
		echo $color;
	}
?></p>
			</div>
		</div>
		<div class="item">
			<label for="p_pic">配图<span>可提高文章人气，请尽量选择与主题贴切、清晰、无水印的图片</span></label>
			<input type="file" id="p_pic" name="p_pic" />
			<?php wp_nonce_field('client-file-upload', 'client-file-upload'); ?>
		</div>
<?php if ( !is_user_logged_in() ): ?>
		<div class="item">
			<label for="p_authorname">昵称<span>如不填则以匿名发表</span></label>
			<input type="text" id="p_authorname" name="p_authorname" />
		</div>
		<div class="item">
			<label for="p_authoremail">邮箱<span>不会被公开，仅为方便联系，请填写真实有效的邮箱地址</span></label>
			<input type="text" id="p_authoremail" name="p_authoremail" />
		</div>
<?php endif; ?>
		<div class="send">
			<input type="hidden" value="send" name="p_form" />
			<input type="submit" value="发表" />
		</div>
	</form>
</div>
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F1c8206f5c5b3ec83c38a99d0ad484e06' type='text/javascript'%3E%3C/script%3E"));
</script>
</body>
</html>